package cn.com.cifi.mars.service.impl;

import cn.com.cifi.mars.bean.bo.SysLogBO;
import cn.com.cifi.mars.bean.dto.FunctionalPermissionDto;
import cn.com.cifi.mars.bean.dto.IdmUserPageDto;
import cn.com.cifi.mars.bean.dto.ProjectByStagesDto;
import cn.com.cifi.mars.bean.vo.sys.rsp.GroupUserVo;
import cn.com.cifi.mars.bean.vo.sys.rsp.IdmUserVo;
import cn.com.cifi.mars.bean.vo.sys.rsp.UserFunctionalPermissionVo;
import cn.com.cifi.mars.constant.*;
import cn.com.cifi.mars.entity.common.IdmUser;
import cn.com.cifi.mars.entity.common.SysUserRole;
import cn.com.cifi.mars.mapper.mars.*;
import cn.com.cifi.mars.service.IdmUserService;
import cn.com.cifi.mars.service.SysLogService;
import cn.com.cifi.mars.util.BasicAuthClient;
import cn.com.cifi.mars.util.FieldUtils;
import cn.com.cifi.mars.util.StrUtils;
import cn.com.cifi.mars.util.WebUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class IdmUserServiceImpl extends ServiceImpl<IdmUserMapper, IdmUser> implements IdmUserService {

    @Autowired
    private IdmUserMapper idmUserMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysPermissionMapper sysPermissionMapper;
    @Autowired
    private SysPositionGroupAuthorizeMapper sysPositionGroupAuthorizeMapper;
    @Autowired
    private ProjectByStagesMapper projectByStagesMapper;
    @Autowired
    private IdmPositionMapper idmPositionMapper;
    @Autowired
    private SysLogService sysLogService;

    @Value("${host}")
    private String host;

    @Value("${port_idm}")
    private String port_idm;

    @Value("${api_name}")
    private String api_name;

    @Value("${api_key}")
    private String api_key;

    @Override
    public IdmUser selectByUserName(String userName) {
        return idmUserMapper.selectByUserName(userName);
    }

    /**
     * 本地用户信息分页
     */
    @Override
    public IdmUserVo queryUserPageList(String current, String pageSize, String departmentnumber, String usercn) {
        IdmUserVo vo = new IdmUserVo();
        Page<IdmUserPageDto> pageDto = new Page<IdmUserPageDto>();
        //参数当前页
        pageDto.setCurrent(Integer.parseInt(current));
        //参数每页数量
        pageDto.setSize(Integer.parseInt(pageSize));

        List<IdmUserPageDto> list = idmUserMapper.selectUserPage(pageDto, departmentnumber, usercn);
        list.forEach(x -> {
            //性别编码 1：男 2：女
            String gender_id = "";
            if (x.getGenderId() != null) {
                gender_id = x.getGenderId().toString();
                if (gender_id.equals(GenderEunm.FEMALE.getKey())) {
                    gender_id = GenderEunm.FEMALE.getValue();
                } else {
                    gender_id = GenderEunm.MALE.getValue();
                }
            }

            //用户类型//E1内部用户，E2 编外员工，O1外部用户，O2外部合作人员，O3供应商人员，O4代理商人员
            String usertype = x.getUsertype();
            if (usertype.equals(UserTypeEunm.E1.getKey())) {
                usertype = UserTypeEunm.E1.getValue();
            } else if (usertype.equals(UserTypeEunm.E2.getKey())) {
                usertype = UserTypeEunm.E2.getValue();
            } else if (usertype.equals(UserTypeEunm.O1.getKey())) {
                usertype = UserTypeEunm.O1.getValue();
            } else if (usertype.equals(UserTypeEunm.O2.getKey())) {
                usertype = UserTypeEunm.O2.getValue();
            } else if (usertype.equals(UserTypeEunm.O3.getKey())) {
                usertype = UserTypeEunm.O3.getValue();
            } else if (usertype.equals(UserTypeEunm.O4.getKey())) {
                usertype = UserTypeEunm.O4.getValue();
            } else {
                usertype = "未知";
            }
            x.setUsertype(usertype);
            x.setGenderId(gender_id);
        });
        vo.setCurrent(pageDto.getCurrent());
        vo.setPages(pageDto.getPages());
        vo.setPageSize(pageDto.getSize());
        vo.setTotal(pageDto.getTotal());
        vo.setList(list);
        return vo;
    }

    /**
     * 获取用户的数据权限->组织机构->项目分期
     */
    @Override
    public List<ProjectByStagesDto> queryUserDataPermissions(String userId) {
        //1.查询用户是否存在角色
        List<SysUserRole> roleList = sysUserRoleMapper.selectByUserId(userId);
        if (roleList.size() > 0) {
            List<ProjectByStagesDto> list = getUserRoleV2(roleList);
            return list;
        } else {
            //2.查询用户是否设置岗位组 岗位权限
            List<ProjectByStagesDto> list = getUserPositionV2(userId);
            return list;
        }
    }

    /**
     * 查用户项目权限
     *
     * @param userId
     * @return
     */
    @Override
    public List<String> queryUserProjectPermissions(String userId) {
        //查数据权限
        List<ProjectByStagesDto> projectByStagesDtos = queryUserDataPermissions(userId);

        List<String> projectIdList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(projectByStagesDtos)) {
            for (ProjectByStagesDto dto : projectByStagesDtos) {
                if (dto.getHrOrgTypeId().equals(HrOrgTypeEunm.ORG_31.getKey())) {
                    projectIdList.add(dto.getOrgdepid());
                }
            }
        }
        return projectIdList;
    }

    /**
     * 查用户事业部权限
     *
     * @param userId
     * @return
     */
    @Override
    public List<String> queryUserDivisionPermissions(String userId) {
        //查数据权限
        List<ProjectByStagesDto> projectByStagesDtos = queryUserDataPermissions(userId);
        List<String> divisionList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(projectByStagesDtos)) {
            projectByStagesDtos.stream()
                    .filter(x -> "事业部".equals(x.getHrOrgType()))
                    .forEach(x -> {
                        divisionList.add(x.getOrgdepid());
                    });
        }
        return divisionList;
    }


    /**
     * 获取用户的功能权限-->菜单
     */
    @Override
    public UserFunctionalPermissionVo queryUserFunctionalPermissions(String userId) {
        //1.查询用户是否存在角色
        List<SysUserRole> roleList = sysUserRoleMapper.selectByUserId(userId);
        if (roleList.size() > 0) {
            UserFunctionalPermissionVo vo = getUserRolePermission(roleList, userId);
            return vo;
        } else {
            //2.查询用户是否设置岗位功能权限
            UserFunctionalPermissionVo vo = getUserPositionPermission(userId);
            return vo;
        }
    }

    /**
     * 优化用户角色,获取角色的功能权限信息
     *
     * @param roleList
     */
    public UserFunctionalPermissionVo getUserRolePermission(List<SysUserRole> roleList, String userId) {
        UserFunctionalPermissionVo vo = new UserFunctionalPermissionVo();
        List<String> roleIds = new ArrayList<>();
        for (SysUserRole role : roleList) {
            String roleId = role.getRoleId();
            roleIds.add(roleId);
        }
        //获取角色权限
        List<FunctionalPermissionDto> list = sysPermissionMapper.selectByRoleIds(roleIds);

        List<FunctionalPermissionDto> menuList = new ArrayList<>();
        List<FunctionalPermissionDto> buttonList = new ArrayList<>();
        List<FunctionalPermissionDto> tabList = new ArrayList<>();


        for (FunctionalPermissionDto x : list) {
            if (x.getPerType().equals(PerTypeEnum.MENU.getKey())) {
                menuList.add(x);
            } else if (x.getPerType().equals(PerTypeEnum.BUTTON.getKey())) {
                buttonList.add(x);
            } else if (x.getPerType().equals(PerTypeEnum.PAGE.getKey())) {
                tabList.add(x);
            }
        }
        vo.setMenus(menuList);
        vo.setButtons(buttonList);
        vo.setTabs(tabList);
        return vo;
    }

    /**
     * 优化 岗位岗位组 功能权限-》功能权限不需要自动授权
     *
     * @return
     */
    public UserFunctionalPermissionVo getUserPositionPermission(String userId) {
        UserFunctionalPermissionVo vo = new UserFunctionalPermissionVo();
        // 根据用户id或者用户信息
        IdmUser user = idmUserMapper.selectByUserName(userId);
        if (user != null) {
            List<String> positionIds = new ArrayList<String>();
            //查询有没有兼职岗位
            if (StringUtils.isNotBlank(user.getParttimepost())) {
                //5.查询是否兼职岗位授权
                String[] post = user.getParttimepost().split(";");
                for (String string : post) {
                    positionIds.add(string);
                }
            }
            String positionId = user.getPositionid();
            if (StrUtils.isNotEmpty(positionId)) {
                positionIds.add(positionId);
            }

            //根据兼职岗位查询岗位组
            List<String> positionGroupIds = new ArrayList<>();
            if (positionIds.size() > 0) {
                positionGroupIds = idmPositionMapper.selectPositionGroupIds(positionIds);
            }
            //根据用户岗位组id 获取岗位组是否授权
            String positionGroupId = user.getIDMJobdefid();
            if (StrUtils.isNotEmpty(positionGroupId)) {
                positionGroupIds.add(positionGroupId);
            }

            //查询岗位组功能权限关联表
            List<FunctionalPermissionDto> list = sysPermissionMapper.selectByPositionGroupId(positionGroupIds);
            List<FunctionalPermissionDto> menuList = new ArrayList<>();
            List<FunctionalPermissionDto> buttonList = new ArrayList<>();
            List<FunctionalPermissionDto> tabList = new ArrayList<>();
            for (FunctionalPermissionDto x : list) {
                if (x.getPerType().equals(PerTypeEnum.MENU.getKey())) {
                    menuList.add(x);
                } else if (x.getPerType().equals(PerTypeEnum.BUTTON.getKey())) {
                    buttonList.add(x);
                } else if (x.getPerType().equals(PerTypeEnum.PAGE.getKey())) {
                    tabList.add(x);
                }
            }
            vo.setMenus(menuList);
            vo.setButtons(buttonList);
            vo.setTabs(tabList);
        }
        return vo;
    }


    /**
     * 优化用户角色,获取角色的组织机构信息->数据权限 项目分期
     *
     * @param roleList
     */
    public List<ProjectByStagesDto> getUserRoleV2(List<SysUserRole> roleList) {
        List<ProjectByStagesDto> dtoList = new ArrayList<>();
        HashSet<ProjectByStagesDto> list = new HashSet<>();
        List<String> roleIds = new ArrayList<>();
        for (SysUserRole role : roleList) {
            String roleId = role.getRoleId();
            roleIds.add(roleId);
        }
        //旭辉集团的 全部查出来
        List<String> xhIds = projectByStagesMapper.selectStagesId(roleIds, HrOrgTypeEunm.ORG_11.getKey());
        //区域的id 全部查出来
        List<String> regionIds = projectByStagesMapper.selectStagesId(roleIds, HrOrgTypeEunm.ORG_20.getKey());
        //城市公司的id 全部查出来
        List<String> cityIds = projectByStagesMapper.selectStagesId(roleIds, HrOrgTypeEunm.ORG_21.getKey());
        //直管项目的id 全部查出来
        List<String> tubeIds = projectByStagesMapper.selectStagesId(roleIds, HrOrgTypeEunm.ORG_23.getKey());
        //项目的id 全部查出来
        List<String> projectIds = projectByStagesMapper.selectStagesId(roleIds, HrOrgTypeEunm.ORG_31.getKey());
        if (xhIds.size() > 0) {
            List<ProjectByStagesDto> xhList = projectByStagesMapper.selectRoleOrgList(xhIds);
            list.addAll(xhList);
        }
        if (regionIds.size() > 0) {
            List<ProjectByStagesDto> regionList = projectByStagesMapper.selectRoleOrgList(regionIds);
            list.addAll(regionList);
        }
        if (cityIds.size() > 0) {
            //根据城市id获取城市和城市以下所有数据
            List<ProjectByStagesDto> cityList = projectByStagesMapper.selectRoleOrgList(cityIds);
            //根据城市id获取区域信息
            List<ProjectByStagesDto> regionList = projectByStagesMapper.selectOrgParentList(cityIds);
            list.addAll(cityList);
            list.addAll(regionList);
        }
        if (tubeIds.size() > 0) {
            //根据直管项目id获取直管项目和以下所有数据
            List<ProjectByStagesDto> tubeList = projectByStagesMapper.selectRoleOrgList(tubeIds);
            //根据直管项目id获取区域信息
            List<ProjectByStagesDto> regionList = projectByStagesMapper.selectOrgParentList(tubeIds);
            list.addAll(tubeList);
            list.addAll(regionList);
        }
        if (projectIds.size() > 0) {
            //根据项目id获取项目和以下所有数据
            List<ProjectByStagesDto> projectList = projectByStagesMapper.selectRoleOrgList(projectIds);
            //根据项目id获取城市公司信息
            List<ProjectByStagesDto> cityList = projectByStagesMapper.selectOrgParentList(projectIds);
            List<String> cityStr = new ArrayList<>();
            for (ProjectByStagesDto c : cityList) {
                cityStr.add(c.getOrgdepid());
            }
            //根据城市公司id获取区域信息
            List<ProjectByStagesDto> regionList = projectByStagesMapper.selectOrgParentList(cityStr);
            list.addAll(projectList);
            list.addAll(cityList);
            list.addAll(regionList);
        }
        dtoList.addAll(list);
        return dtoList;
    }


    /**
     * 优化用户岗位,岗位组,获取岗位,岗位组的组织机构信息->项目分期树
     * 数据权限到岗位->设置自动授权后就有他的岗位组数据权限
     *
     * @param roleList
     */
    public List<ProjectByStagesDto> getUserPositionV2(String userId) {
        List<ProjectByStagesDto> dtoList = new ArrayList<>();
        // 根据用户id或者用户信息
        IdmUser user = idmUserMapper.selectByUserName(userId);
        HashSet<ProjectByStagesDto> list = new HashSet<>();
        List<ProjectByStagesDto> groupList = new ArrayList<>();
        List<String> positionIds = new ArrayList<>();
        List<ProjectByStagesDto> positionList = new ArrayList<>();
        if (user != null) {
            //查询有没有兼职岗位
            if (StringUtils.isNotBlank(user.getParttimepost())) {
                //5.查询是否兼职岗位授权
                String[] post = user.getParttimepost().split(";");
                for (String string : post) {
                    positionIds.add(string);
                }
            }
            if (StringUtils.isNotBlank(user.getPositionid())) {
                positionIds.add(user.getPositionid());
            }
            //根据兼职岗位查询岗位组
            List<String> positionGroupIds = new ArrayList<>();
            if (positionIds.size() > 0) {
                positionGroupIds = idmPositionMapper.selectPositionGroupIds(positionIds);
            }

            if (StringUtils.isNotBlank(user.getIDMJobdefid())) {
                positionGroupIds.add(user.getIDMJobdefid());
            }

            //根据多个岗位组id查询只授权的岗位id集合
            List<String> positionIdList = sysPositionGroupAuthorizeMapper.selectByPositionGroupIds(positionGroupIds, positionIds);
            for (String posiId : positionIdList) {
                //只查授权的岗位组下的岗位id
                List<String> orgids = getGroupOrgIds(posiId);
                if (CollectionUtils.isNotEmpty(orgids)) {
                    List<ProjectByStagesDto> psdList = getPositionGroupList(orgids);
                    groupList.addAll(psdList);
                }

            }
            positionList = getPositionListV2(positionIds);
        }
        list.addAll(groupList);
        list.addAll(positionList);
        dtoList.addAll(list);
        return dtoList;
    }


    /**
     * 优化岗位,兼职岗位->数据权限
     *
     * @param pbs
     * @return
     */
    public List<ProjectByStagesDto> getPositionListV2(List<String> positionIds) {
        List<ProjectByStagesDto> dtoList = new ArrayList<>();
        if (positionIds.size() == 0) {
            return dtoList;
        }
        HashSet<ProjectByStagesDto> list = new HashSet<>();

        //旭辉集团的 全部查出来
        List<String> xhIds = projectByStagesMapper.selectStagesByPositionIds(positionIds, HrOrgTypeEunm.ORG_11.getKey());
        //区域的id 全部查出来
        List<String> regionIds = projectByStagesMapper.selectStagesByPositionIds(positionIds, HrOrgTypeEunm.ORG_20.getKey());
        //城市公司的id 全部查出来
        List<String> cityIds = projectByStagesMapper.selectStagesByPositionIds(positionIds, HrOrgTypeEunm.ORG_21.getKey());
        //直管项目的id 全部查出来
        List<String> tubeIds = projectByStagesMapper.selectStagesByPositionIds(positionIds, HrOrgTypeEunm.ORG_23.getKey());
        //项目的id 全部查出来
        List<String> projectIds = projectByStagesMapper.selectStagesByPositionIds(positionIds, HrOrgTypeEunm.ORG_31.getKey());

        if (xhIds.size() > 0) {
            List<ProjectByStagesDto> xhList = projectByStagesMapper.selectRoleOrgList(xhIds);
            list.addAll(xhList);
        }
        if (regionIds.size() > 0) {
            List<ProjectByStagesDto> regionList = projectByStagesMapper.selectRoleOrgList(regionIds);
            list.addAll(regionList);
        }
        if (cityIds.size() > 0) {
            //根据城市id获取城市和城市以下所有数据
            List<ProjectByStagesDto> cityList = projectByStagesMapper.selectRoleOrgList(cityIds);
            //根据城市id获取区域信息
            List<ProjectByStagesDto> regionList = projectByStagesMapper.selectOrgParentList(cityIds);
            list.addAll(cityList);
            list.addAll(regionList);
        }
        if (tubeIds.size() > 0) {
            //根据直管项目id获取直管项目和以下所有数据
            List<ProjectByStagesDto> tubeList = projectByStagesMapper.selectRoleOrgList(tubeIds);
            //根据直管项目id获取区域信息
            List<ProjectByStagesDto> regionList = projectByStagesMapper.selectOrgParentList(tubeIds);
            list.addAll(tubeList);
            list.addAll(regionList);
        }
        if (projectIds.size() > 0) {
            //根据项目id获取项目和以下所有数据
            List<ProjectByStagesDto> projectList = projectByStagesMapper.selectRoleOrgList(projectIds);
            //根据项目id获取城市公司信息
            List<ProjectByStagesDto> cityList = projectByStagesMapper.selectOrgParentList(projectIds);
            List<String> cityStr = new ArrayList<>();
            for (ProjectByStagesDto c : cityList) {
                cityStr.add(c.getOrgdepid());
            }
            //根据城市公司id获取区域信息
            List<ProjectByStagesDto> regionList = projectByStagesMapper.selectOrgParentList(cityStr);
            list.addAll(projectList);
            list.addAll(cityList);
            list.addAll(regionList);
        }
        dtoList.addAll(list);
        return dtoList;
    }

    /**
     * 获取自动授权的岗位组的组织机构id
     *
     * @param orgnofullpath
     * @return
     */
    public List<String> getGroupOrgIds(String positionId) {
        List<String> orgids = new ArrayList<>();
        String belongDepFullNo = idmPositionMapper.selectBelongDepFullNoList(positionId);
        if (!StringUtils.isNotBlank(belongDepFullNo)) {
            return orgids;
        }
        String[] path = belongDepFullNo.split("-");
        //根据岗位id获取部门全路径信息
        String belongDepFullName = idmPositionMapper.selectBelongDepFullNameList(positionId);
        if (belongDepFullName.contains("期")) {
            //不在我们本地数据库的分期 不显示出来
            String stagesId = path[belongDepFullNo.split("-").length - 1];
            ProjectByStagesDto bb = projectByStagesMapper.selectByOrgdepid(stagesId);
            if (null == bb) {
                return orgids;
            }
        }

        for (int i = path.length - 1; i >= 0; i--) {
            String str = path[i];
            ProjectByStagesDto bb = projectByStagesMapper.selectByOrgdepid(str);
            if (bb != null) {
                if (StringUtils.isNotBlank(bb.getHrOrgTypeId())) {
                    if (bb.getHrOrgTypeId().equals(HrOrgTypeEunm.ORG_31.getKey())) {
                        orgids.add(str);
                        break;
                    } else if (bb.getHrOrgTypeId().equals(HrOrgTypeEunm.ORG_23.getKey())) {
                        orgids.add(str);
                        break;
                    } else if (bb.getHrOrgTypeId().equals(HrOrgTypeEunm.ORG_21.getKey())) {
                        orgids.add(str);
                        break;
                    } else if (bb.getHrOrgTypeId().equals(HrOrgTypeEunm.ORG_20.getKey())) {
                        orgids.add(str);
                        break;
                    } else if (bb.getHrOrgTypeId().equals(HrOrgTypeEunm.ORG_11.getKey())) {
                        orgids.add(str);
                        break;
                    }
                }
            }
        }
        return orgids;
    }


    /**
     * 优化岗位组->数据权限-》自动授权的组织机构权限
     *
     * @param pbs
     * @return
     */
    public List<ProjectByStagesDto> getPositionGroupList(List<String> positionIds) {
        List<ProjectByStagesDto> dtoList = new ArrayList<>();
        if (positionIds.size() == 0) {
            return dtoList;
        }
        HashSet<ProjectByStagesDto> list = new HashSet<>();

        //旭辉集团的 全部查出来
        List<String> xhIds = projectByStagesMapper.selectStagesByPositionGroupIds(positionIds, HrOrgTypeEunm.ORG_11.getKey());
        //区域的id 全部查出来
        List<String> regionIds = projectByStagesMapper.selectStagesByPositionGroupIds(positionIds, HrOrgTypeEunm.ORG_20.getKey());
        //城市公司的id 全部查出来
        List<String> cityIds = projectByStagesMapper.selectStagesByPositionGroupIds(positionIds, HrOrgTypeEunm.ORG_21.getKey());
        //直管项目的id 全部查出来
        List<String> tubeIds = projectByStagesMapper.selectStagesByPositionGroupIds(positionIds, HrOrgTypeEunm.ORG_23.getKey());
        //项目的id 全部查出来
        List<String> projectIds = projectByStagesMapper.selectStagesByPositionGroupIds(positionIds, HrOrgTypeEunm.ORG_31.getKey());

        if (xhIds.size() > 0) {
            List<ProjectByStagesDto> xhList = projectByStagesMapper.selectRoleOrgList(xhIds);
            list.addAll(xhList);
        }
        if (regionIds.size() > 0) {
            List<ProjectByStagesDto> regionList = projectByStagesMapper.selectRoleOrgList(regionIds);
            list.addAll(regionList);
        }
        if (cityIds.size() > 0) {
            //根据城市id获取城市和城市以下所有数据
            List<ProjectByStagesDto> cityList = projectByStagesMapper.selectRoleOrgList(cityIds);
            //根据城市id获取区域信息
            List<ProjectByStagesDto> regionList = projectByStagesMapper.selectOrgParentList(cityIds);
            list.addAll(cityList);
            list.addAll(regionList);
        }
        if (tubeIds.size() > 0) {
            //根据直管项目id获取直管项目和以下所有数据
            List<ProjectByStagesDto> tubeList = projectByStagesMapper.selectRoleOrgList(tubeIds);
            //根据直管项目id获取区域信息
            List<ProjectByStagesDto> regionList = projectByStagesMapper.selectOrgParentList(tubeIds);
            list.addAll(tubeList);
            list.addAll(regionList);
        }
        if (projectIds.size() > 0) {
            //根据项目id获取项目和以下所有数据
            List<ProjectByStagesDto> projectList = projectByStagesMapper.selectRoleOrgList(projectIds);
            //根据项目id获取城市公司信息
            List<ProjectByStagesDto> cityList = projectByStagesMapper.selectOrgParentList(projectIds);
            List<String> cityStr = new ArrayList<>();
            for (ProjectByStagesDto c : cityList) {
                cityStr.add(c.getOrgdepid());
            }
            //根据城市公司id获取区域信息
            List<ProjectByStagesDto> regionList = projectByStagesMapper.selectOrgParentList(cityStr);
            list.addAll(projectList);
            list.addAll(cityList);
            list.addAll(regionList);
        }
        dtoList.addAll(list);
        return dtoList;
    }

    /**
     * 根据组织机构id和岗位组id查询对应的用户信息
     *
     * @return
     */
    @Override
    public HashSet<GroupUserVo> getGroupUserInfo(String positionGroupId, String orgdepid) {
        HashSet<GroupUserVo> set = new HashSet<>();
        List<GroupUserVo> list = new ArrayList<>();
        //查询岗位ids
        List<String> jobNums = idmPositionMapper.selectJobNum(positionGroupId, orgdepid);
        if (jobNums.size() == 0) {
            return set;
        }
        //根据岗位ids查询用户信息
        list = idmUserMapper.selectByJobNums(jobNums);
        set.addAll(list);
        return set;
    }

    /**
     * 根据时间增量同步用户信息
     */
    @Override
    public String syncUser(String time, String cookie, String alias) {
        List<IdmUser> userList = idmUserMapper.selectUserList();
        Map<String, String> map = new HashMap<>();
        do {
            map = incrementUser(time, cookie, alias, userList);
            cookie = map.get("ck");
            saveLog(map.get("msg"), "增量同步用户信息");
        } while (StringUtils.isNotBlank(cookie));

        return map.get("msg");
    }

    /**
     * 同步增量用户方法
     */
    public Map<String, String> incrementUser(String time, String cookie, String alias, List<IdmUser> userAllList) {
        Map<String, String> map = new HashMap<>();
        BasicAuthClient bac = new BasicAuthClient();
        String api = "/idm/users/query?filter=";
        String url = host + api;
        String filter = "*".equals(alias) ? "(&(alias=" + alias + ")(|(usercreatetime>=" + time + ")(modifytimestamp>=" + time + ")))" : "(&(alias=" + alias + "))";
        try {
            filter = URLEncoder.encode(filter, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.error("###### errorMsg: ", e);
        }
        if ("0".equals(cookie) || "null".equals(cookie) || StringUtils.isBlank(cookie)) {
            filter = filter + "&pageSize=" + 1000;
        } else {
            filter = filter + "&pageSize=" + 1000 + "&cookie=" + cookie;
        }
        String result = bac.get(url, filter, api_name, api_key);
        log.info("######### 同步用户数据请求参数：" + url + filter);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (jsonObject != null) {
            if (jsonObject.getJSONObject("esbInfo") != null) {
                JSONObject esbInfo = jsonObject.getJSONObject("esbInfo");
                String returnMsg = esbInfo.getString("returnMsg");
                if (returnMsg.equals("success")) {
                    JSONObject resultInfo = jsonObject.getJSONObject("resultInfo");
                    JSONObject body = (JSONObject) resultInfo.get("body");
                    JSONArray wsUsers = body.getJSONArray("wsUsers");
                    if (wsUsers != null && !wsUsers.isEmpty()) {
                        List<IdmUser> userList = fillUserList(wsUsers);
                        updateOrSaveUsers(userList, userAllList);
                        map.put("ck", body.getString("cookie"));
                        map.put("msg", prepareSyncUser(userList));
                    }
                } else {
                    map.put("msg", returnMsg);
                    return map;
                }
            }
        }
        return map;
    }

    private String prepareSyncUser(List<IdmUser> userList) {
        StringBuilder sb = new StringBuilder();
        for (IdmUser user : userList) {
            sb.append(user.getAlias()).append(user.getUsercn()).append(";");
        }
        return sb.toString();
    }

    private List<IdmUser> fillUserList(JSONArray wsUsers) {
        List<IdmUser> userList = new ArrayList<>();
        for (int i = 0; i < wsUsers.size(); i++) {
            JSONObject attributes = wsUsers.getJSONObject(i);
            JSONArray attributesArray = (JSONArray) attributes.get("attributes");
            IdmUser user = new IdmUser();
            for (int j = 0; j < attributesArray.size(); j++) {
                JSONObject kObj = attributesArray.getJSONObject(j);
                String name = kObj.get("name").toString();
                String value = "";
                if (kObj.get("value") != null) {
                    value = kObj.get("value").toString();
                }
                if (kObj.get("values") != null) {
                    value = kObj.get("values").toString();
                }
                FieldUtils.setProperty(user, name.replaceAll("-", "_"), value);
            }
            userList.add(user);
        }

        return userList;
    }

    private void updateOrSaveUsers(List<IdmUser> userList, List<IdmUser> userAllList) {
        List<IdmUser> updUserList = new ArrayList<>();
        List<IdmUser> addUserList = new ArrayList<>();
        for (IdmUser user : userList) {
            if (isExistUser(user.getAlias(), userAllList)) {
                updUserList.add(user);
            } else {
                addUserList.add(user);
            }
        }
        if (CollectionUtils.isNotEmpty(addUserList)) {
            idmUserMapper.insertList(addUserList);
        }
        if (CollectionUtils.isNotEmpty(updUserList)) {
            idmUserMapper.updateBatch(updUserList);
        }

    }

    private boolean isExistUser(String alias, List<IdmUser> userAllList) {
        for (IdmUser user : userAllList) {
            if (alias.equals(user.getAlias())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 添加日志
     */
    private void saveLog(String content, String title) {
        SysLogBO bo = new SysLogBO();
        bo.setEvent(LogEventEnum.TIMERTASK);
        bo.setSource(LogSrcEnum.SYS);
        String hostAddr = WebUtils.getLocalIP();
        bo.setIp(hostAddr);
        bo.setModule("同步用户信息");
        bo.setTitle(title);
        bo.setContent(content);
        bo.setType(LogTypeEnum.ONE.getKey());
        bo.setIsSuccess(IsSuccessEnum.SUCCESS.getKey());
        sysLogService.add(bo, Constants.SYS);
    }

    /**
     * 获取岗位组对应的用户信息
     *
     * @param positionGroupId 岗位组Id
     * @param orgdepid        组织id
     * @return
     */
    @Override
    public List<IdmUser> getPositionGroupUserList(String positionGroupId, String orgdepid) {
        List<String> aliasList = new ArrayList<>();
        HashSet<GroupUserVo> set = getGroupUserInfo(positionGroupId, orgdepid);
        if (CollectionUtils.isNotEmpty(set)) {
            aliasList = set.stream().map(GroupUserVo::getAlias).collect(Collectors.toList());
        }
        return getByAliasList(aliasList);
    }

    /**
     * 根据账号获取用户信息
     *
     * @param alias 账号
     * @return
     */
    @Override
    public IdmUser getByAlias(String alias) {
        QueryWrapper<IdmUser> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("alias", alias);
        IdmUser idmUser = idmUserMapper.selectOne(userQueryWrapper);
        return idmUser;
    }

    /**
     * 根据账号获取用户信息，限制查询一条
     *
     * @param alias 账号
     * @return
     */
    @Override
    public IdmUser getByAliasLimitOne(String alias) {
        QueryWrapper<IdmUser> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("alias", alias).last("limit 1");
        IdmUser idmUser = idmUserMapper.selectOne(userQueryWrapper);
        return idmUser;
    }

    /**
     * 根据账号列表获取用户信息
     *
     * @param aliasList 账号列表
     * @return
     */
    @Override
    public List<IdmUser> getByAliasList(List<String> aliasList) {
        if (CollectionUtils.isEmpty(aliasList)) {
            return new ArrayList<>();
        }
        QueryWrapper<IdmUser> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.in("alias", aliasList);
        return idmUserMapper.selectList(userQueryWrapper);
    }
}
